import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import { fileURLToPath } from 'url';
import path from 'path';

// 环境变量加载说明：
// config/config.js 中已经加载了环境变量，这里不需要重复加载
// 确保所有环境变量管理统一在项目根目录的 .env 文件中

// 导入统一配置和工具
import config from '../../config/config.js';
import { logger, requestLogger, errorLogger, performanceLogger } from '../../utils/logger.js';
import { requestMonitoring, startMetricsCollection, metricsEndpoint, healthCheckEndpoint } from '../../utils/monitoring.js';

// 导入数据库和缓存
import { dbPool, redisClient, testDatabaseConnection, testRedisConnection, gracefulShutdown } from '../config/database.js';

// 导入路由
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import productRoutes from './routes/products.js';
import bikeProductRoutes from './routes/bike-products.js';

import dashboardRoutes from './routes/dashboard.js';

// 导入博客相关路由
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const articlesApi = require('./services/articles-api.js');
const blogCategoriesApi = require('./services/blog-categories-api.js');
const blogColumnsApi = require('./services/blog-columns-api.js');
const commentsApi = require('./services/comments-api.js');

// 导入图库相关路由
const galleryApi = require('./services/gallery-api.js');

// 导入专门的图片管理API路由
const carouselApi = require('./services/carousel-api.js');
const logoApi = require('./services/logo-api.js');
const productImagesApi = require('./services/product-images-api.js');
const blogImagesApi = require('./services/blog-images-api.js');

// 导入系统设置API路由
const systemSettingsApi = require('./services/system-settings-api.js');

// 导入国际化多语言API路由
const i18nApi = require('./services/i18n-api.js');

// 导入API翻译服务路由
const translationApi = require('./services/translation-api.js');

// 导入博客多语言API路由
const blogI18nApi = require('./services/blog-i18n-api.js');

// 导入博客翻译API路由
const blogTranslationApi = require('./services/blog-translation-api.js');

// 导入仪表盘指标API路由
const dashboardMetricsApi = require('./services/dashboard-metrics-api.js');

const app = express();
const PORT = config.servers.backend.port;

// 中间件配置 - 生产环境安全加固
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", "'unsafe-inline'", "https://cdn.bootcdn.net"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://cdn.bootcdn.net"],
      imgSrc: ["'self'", "data:", "https:"],
      fontSrc: ["'self'", "https://cdn.bootcdn.net"]
    }
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true
  }
}));

app.use(compression({ threshold: config.performance.compression.threshold }));
app.use(morgan('combined', {
  skip: (req, res) => req.path === '/health' // 跳过健康检查日志
}));
app.use(cors({
  origin: config.security.cors.allowedOrigins,
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));

// 请求体大小限制
app.use(express.json({ 
  limit: '10mb',
  verify: (req, res, buf) => {
    // 防止JSON注入攻击
    try {
      JSON.parse(buf.toString());
    } catch (e) {
      throw new Error('Invalid JSON');
    }
  }
}));
app.use(express.urlencoded({ 
  extended: true,
  limit: '10mb'
}));

// 统一日志和监控
app.use(requestLogger);
app.use(requestMonitoring);

// 速率限制
const apiLimiter = rateLimit({
  windowMs: config.security.rateLimit.windowMs,
  max: config.security.rateLimit.maxRequests,
  message: '请求过于频繁，请稍后再试'
});
app.use('/api/', apiLimiter);

// 监控端点
if (config.monitoring.enabled) {
  app.get('/metrics', metricsEndpoint);
}

// 健康检查
app.get('/health', async (req, res) => {
  const healthStatus = {
    status: 'healthy',
    timestamp: new Date().toISOString(),
    version: config.app.version,
    services: {}
  };
  
  try {
    // 检查数据库连接
    const dbHealthy = await testDatabaseConnection();
    healthStatus.services.database = dbHealthy ? 'connected' : 'disconnected';
  } catch (dbError) {
    healthStatus.services.database = 'disconnected';
    healthStatus.services.databaseError = dbError.message;
  }
  
  try {
    // 检查Redis连接
    const redisHealthy = await testRedisConnection();
    healthStatus.services.redis = redisHealthy ? 'connected' : 'disconnected';
  } catch (redisError) {
    healthStatus.services.redis = 'disconnected';
    healthStatus.services.redisError = redisError.message;
  }
  
  // 如果所有服务都不可用，标记为不健康
  if (healthStatus.services.database === 'disconnected' && healthStatus.services.redis === 'disconnected') {
    healthStatus.status = 'degraded';
  }
  
  res.json(healthStatus);
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);
app.use('/api/bike-products', bikeProductRoutes);

app.use('/api/dashboard', dashboardRoutes);

// 博客相关API路由
app.use('/api', articlesApi);
app.use('/api', blogCategoriesApi);
app.use('/api', blogColumnsApi);
app.use('/api', commentsApi);

// 图库相关API路由
app.use('/api', galleryApi);

// 专门的图片管理API路由
app.use('/api', carouselApi);
app.use('/api', logoApi);
app.use('/api', productImagesApi);
app.use('/api', blogImagesApi);

// 系统设置API路由
app.use('/api', systemSettingsApi);

// 国际化多语言API路由
app.use('/api', i18nApi);

// API翻译服务路由
app.use('/api', translationApi);

// 博客多语言API路由
app.use('/api', blogI18nApi);

// 博客翻译API路由
app.use('/api', blogTranslationApi);

// 仪表盘指标API路由
app.use('/api', dashboardMetricsApi);

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  
  if (error.name === 'ValidationError') {
    return res.status(400).json({
      success: false,
      message: '输入数据验证失败',
      errors: error.details
    });
  }
  
  if (error.code === '23505') { // PostgreSQL唯一约束违反
    return res.status(409).json({
      success: false,
      message: '数据已存在'
    });
  }
  
  res.status(500).json({
    success: false,
    message: process.env.NODE_ENV === 'production' ? '服务器内部错误' : error.message
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 全局错误处理
process.on('uncaughtException', (error) => {
  console.error('❌ 未捕获的异常:', error.message);
  console.error('堆栈跟踪:', error.stack);
  console.log('💡 服务器将继续运行，但建议重启以清理状态');
});

process.on('unhandledRejection', (reason, promise) => {
  console.warn('⚠️ 未处理的Promise拒绝:', reason);
  console.log('💡 建议检查相关异步操作');
});

// 启动服务器
async function startServer() {
  try {
    console.log('🔧 正在启动Node.js后端服务器...');
    
    // 后台测试数据库连接（不阻塞启动）
    console.log('🔗 后台测试数据库连接...');
    let dbConnected = false;
    
    // 使用超时机制，避免无限等待
    const dbTestPromise = testDatabaseConnection().then(() => {
      console.log('✅ 数据库连接成功');
      dbConnected = true;
      
      // 初始化数据库表结构
      import('../config/database.js').then(({ initializeDatabase }) => {
        initializeDatabase().then(() => {
          console.log('✅ 数据库表结构初始化完成');
        }).catch(initError => {
          console.warn('⚠️ 数据库表结构初始化失败:', initError.message);
        });
      }).catch(importError => {
        console.warn('⚠️ 无法导入数据库初始化模块:', importError.message);
      });
    }).catch(dbError => {
      console.warn('⚠️ 数据库连接失败，服务器将以降级模式运行:', dbError.message);
      console.log('💡 部分功能可能不可用，但API服务仍可运行');
    });
    
    // 设置数据库连接超时（10秒）
    setTimeout(() => {
      if (!dbConnected) {
        console.log('⏰ 数据库连接超时，继续启动服务...');
      }
    }, 10000);
    
    // 后台测试Redis连接
    console.log('🔗 后台测试Redis连接...');
    let redisConnected = false;
    testRedisConnection().then(() => {
      console.log('✅ Redis连接成功');
      redisConnected = true;
    }).catch(redisError => {
      console.warn('⚠️ Redis连接失败，缓存功能不可用:', redisError.message);
    });
    
    // 启动服务器（无论数据库连接是否成功）
    const server = app.listen(PORT, () => {
      console.log(`🚀 Node.js后端服务器运行在 http://localhost:${PORT}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
      console.log(`🔗 API文档: http://localhost:${PORT}/api`);
      console.log('📝 日志系统已启用，日志文件保存在 logs/ 目录');
      
      if (dbConnected && redisConnected) {
        console.log('✅ 服务器已完全启动，所有服务连接正常');
      } else {
        console.log('⚠️ 服务器已启动，部分功能处于降级模式');
      }
    });
    
    // 服务器错误处理
    server.on('error', (error) => {
      if (error.code === 'EADDRINUSE') {
        console.error(`❌ 端口 ${PORT} 已被占用，请检查是否有其他服务在运行`);
      } else {
        console.error('❌ 服务器错误:', error.message);
      }
      process.exit(1);
    });
    
    return server;
  } catch (error) {
    console.error('❌ 服务器启动失败:', error.message);
    console.log('💡 请检查端口是否被占用或其他配置问题');
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', async () => {
  console.log('收到SIGTERM信号，正在关闭服务器...');
  await redisClient.quit();
  await dbPool.end();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.log('收到SIGINT信号，正在关闭服务器...');
  await redisClient.quit();
  await dbPool.end();
  process.exit(0);
});

export default app;

// 启动服务器
if (import.meta.url === `file://${process.argv[1]}`) {
  startServer().catch(error => {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  });
}